package com.xhc.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {
    private static final int QR_CODE_SIZE = 110;
    private static final int MARGIN = 0;
    private static final int TEXT_HEIGHT = 60;
    private static final int PADDING = 1;
    private static final int QR_MARGIN_LEFT = 10;
    private static final int QR_MARGIN_RIGHT = 10;
    private static final int QR_MARGIN_TOP = 0;

    public static byte[] generateQRCodeImage(String qrContent, String displayText,
                                             String boxRange, String boxType) throws WriterException {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, MARGIN);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 生成二维码矩阵
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE,
                QR_CODE_SIZE, QR_CODE_SIZE, hints);

        // 创建带文本的完整图像
        BufferedImage image = createQRImageWithText(bitMatrix, displayText, boxRange, boxType);

        // 转换为字节数组
        return convertImageToBytes(image);
    }

    private static BufferedImage createQRImageWithText(BitMatrix bitMatrix, String text,
                                                       String boxRange, String boxType) {
        // 计算总高度：二维码高度 + 上方边距 + 文本区域高度
        int totalHeight = QR_MARGIN_TOP + QR_CODE_SIZE + TEXT_HEIGHT;

        // 计算总宽度：左侧边距 + 二维码宽度 + 右侧边距
        int totalWidth = QR_MARGIN_LEFT + QR_CODE_SIZE + QR_MARGIN_RIGHT;

        // 创建完整图像
        BufferedImage image = new BufferedImage(
                totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics = image.createGraphics();

        // 设置背景为白色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, totalWidth, totalHeight);

        // 绘制二维码（添加边距）
        graphics.setColor(Color.BLACK);
        for (int x = 0; x < QR_CODE_SIZE; x++) {
            for (int y = 0; y < QR_CODE_SIZE; y++) {
                if (bitMatrix.get(x, y)) {
                    // 应用边距：左侧和上方
                    graphics.fillRect(x + QR_MARGIN_LEFT, y + QR_MARGIN_TOP, 1, 1);
                }
            }
        }

        // 绘制文本
        drawText(graphics, text, boxRange, boxType, totalWidth, totalHeight);

        graphics.dispose();
        return image;
    }

    private static void drawText(Graphics2D graphics, String text, String boxRange,
                                 String boxType, int width, int totalHeight) {
        // 设置字体和颜色 - 使用支持中文的字体
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 使用支持中文的字体
        Font font = new Font("Microsoft YaHei", Font.PLAIN, 10);
        graphics.setFont(font);
        graphics.setColor(Color.BLACK);

        FontMetrics fontMetrics = graphics.getFontMetrics();
        int lineHeight = fontMetrics.getHeight();

        // 解析文本
        String[] parts = text.split(" / ", 2);
        String orderNo = parts.length > 0 ? parts[0] : ""; // A列数据 - 签订单
        String planDate = parts.length > 1 ? parts[1] : ""; // B列数据 - 计划日期

        // 计算文本起始Y位置（在二维码下方）
        int textY = QR_MARGIN_TOP + QR_CODE_SIZE + PADDING + fontMetrics.getAscent();

        // 绘制文本 - 左对齐（考虑左侧边距）
        int leftMargin = QR_MARGIN_LEFT;

        // 第一行文本 - 签订单
        graphics.drawString("签订单: " + orderNo, leftMargin, textY);

        // 第二行文本 - 计划日期
        graphics.drawString("计划日期: " + planDate, leftMargin, textY + lineHeight);

        // 第三行文本 - 箱号段（C列和D列用"-"拼接）
        graphics.drawString("箱号段: " + boxRange, leftMargin, textY + lineHeight * 2);

        // 第四行文本 - 箱型（E列）
        graphics.drawString("箱型: " + boxType, leftMargin, textY + lineHeight * 3);
    }

    private static byte[] convertImageToBytes(BufferedImage image) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            return baos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("无法生成二维码图片: " + e.getMessage());
        }
    }
}